<template>
  <div class="page_content daraBoardStreetAnalysis_content">
    <div class="header_box p-12 bold flex flex-ac flex-jsb">
      <div class="title flex flex-ac">
        <div class="mr-30">车牌列表</div>

      </div>
      <div class="flex flex-ac">
        <!-- <el-icon class="add_icon" :size="20" @click="handleAddClick">
            <CirclePlus />
          </el-icon> -->
        <el-button @click="handleAllDetailsClick" type="success" size="small" :icon="View" class="mr-10">
          详情
        </el-button>
        <el-button @click="handleAddClick" type="primary" size="small" :icon="Plus">新增</el-button>
        <div class="dots flex flex-c flex-jc flex-ac ml-10">
          <span>.</span>
          <span>.</span>
          <span>.</span>
        </div>
      </div>
    </div>
    <div class="main_box m-10 grid">
      <el-table ref="singleTable" :data="tableData" max-height="340" style="width: 100%" fit :header-cell-style="{
          color: '#000',
          background: '#f2f2f2',
        }">
        <el-table-column prop="license_number" label="车牌号" align="center">
        </el-table-column>
        <el-table-column prop="vehicle_type" label="车辆种类" align="center">
          <template #default="scope">
            <span v-if="scope.row.vehicle_type == 0">钩臂箱体运输车</span>
            <span v-else-if="scope.row.vehicle_type == 1">厨余垃圾清运车</span>
            <span v-else-if="scope.row.vehicle_type == 2">大件垃圾清运车</span>
            <span v-else-if="scope.row.vehicle_type == 3">其他垃圾驳运车</span>
            <span v-else-if="scope.row.vehicle_type == 4">厨余垃圾驳运车</span>
            <span v-else-if="scope.row.vehicle_type == 5">三轮垃圾驳运车</span>
            <span v-else-if="scope.row.vehicle_type == 6">维修作业车</span>
            <span v-else-if="scope.row.vehicle_type == 7">管理工作车</span>
          </template>
        </el-table-column>
        <el-table-column prop="recording_time" label="通勤到期时间" align="center" min-width="110">
          <template #default="{ row }">
            {{ formatDateDay(row.recording_time) }}
          </template>

        </el-table-column>

        <el-table-column prop="default" label="操作" width="134" fixed="right" align="center">
          <template #default="scope">
            <el-button @click="handleDetailsClick(scope.row)" type="success" size="small">
              详情
            </el-button>
            <el-button @click="handleEditClick(scope.row)" type="primary" size="small">编辑</el-button>
            <!-- <el-popconfirm
              width="220"
              :icon="WarningFilled"
              icon-color="#f56c6c"
              title="是否确认删除"
              confirm-button-type="danger"
              @confirm="handleDelClick(scope.row)"
              placement="top"
              cancel-button-type="primary"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <!~~ @click="handleDelClick(scope.row)" ~~>
                <el-button type="danger" size="small">删除</el-button>
              </template>
  </el-popconfirm>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增   -->
    <el-dialog title="车辆牌照添加表" v-model="dialogAddVisible" width="50%" draggable align-center destroy-on-close
      class="dialog_add" :before-close="handleClose">
      <el-form ref="formRef" :model="form" label-width="90px" label-position="top" class="dialog_addform"
        :rules="rules">
        <el-form-item label="展示号码" prop="licenseNumber" name='licenseNumber'>
          <el-input v-model="form.licenseNumber" maxlength="10" show-word-limit placeholder="请输入展示号码" clearable
            style="width: 100%" :disabled="form.disabled"></el-input>
        </el-form-item>

        <el-form-item label="车辆种类" prop="vehicleType" name='vehicleType'>
          <el-select :disabled="form.disabled" v-model="form.vehicleType" placeholder="请选择车辆种类" size="large"
            style="width: 100%" clearable>
            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="licenseKind" name='licenseKind'>
          <!-- <el-input v-model="form.value.licenseKind" maxlength="10" show-word-limit placeholder="请输入车辆类型" clearable
            style="width: 100%"></el-input> -->
          <el-autocomplete :disabled="form.disabled" v-model="form.licenseKind"
            :fetch-suggestions="licenseKindQuerySearchAsync" placeholder="请输入车辆类型" key="licenseKind"
            style="width: 100%"></el-autocomplete>
        </el-form-item>
        <el-form-item label="车辆容积" prop="volume" name='volume'>
          <el-input :disabled="form.disabled" v-model="form.volume" maxlength="10" show-word-limit placeholder="请输入车辆容积"
            clearable style="width: 100%"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog title="车辆牌库详情" v-model="dialogVisible" width="70%" draggable align-center destroy-on-close
      :before-close="handleVisibleClose">

      <div class="dialog_header mb-20">
        <el-select class="select mr-10" v-model="selectObj.vehicleType" placeholder="请选择车辆种类" size="large"
          style="width:180px" clearable>
          <el-option v-for="item in unitAllOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="selectObj.key" maxlength="20" placeholder="请输入车牌号或车辆类型或车属单位" clearable
          style="width: 260px"></el-input>
        <el-button class="ml-5 mr-5" @click="handleSelectClose" type="primary">搜索</el-button>
        <el-button @click="handleReact" type="primary">重置</el-button>
      </div>
      <el-table ref="singleTable" :data="tableAllData" height="340" max-height="340" style="width: 100%" fit
        :header-cell-style="{
          color: '#000',
          background: '#f2f2f2',
        }">
        <el-table-column prop="license_number" label="车牌号" align="center">
        </el-table-column>
        <el-table-column prop="vehicle_type" label="车辆种类" align="center">
          <template #default="scope">
            <span v-if="scope.row.vehicle_type == 0">钩臂箱体运输车</span>
            <span v-else-if="scope.row.vehicle_type == 1">厨余垃圾清运车</span>
            <span v-else-if="scope.row.vehicle_type == 2">大件垃圾清运车</span>
            <span v-else-if="scope.row.vehicle_type == 3">其他垃圾驳运车</span>
            <span v-else-if="scope.row.vehicle_type == 4">厨余垃圾驳运车</span>
            <span v-else-if="scope.row.vehicle_type == 5">三轮垃圾驳运车</span>
            <span v-else-if="scope.row.vehicle_type == 6">维修作业车</span>
            <span v-else-if="scope.row.vehicle_type == 7">管理工作车</span>
          </template>
        </el-table-column>
        <el-table-column prop="recording_time" label="通勤到期时间" align="center" min-width="110">
          <template #default="{ row }">
            {{ formatDateDay(row.recording_time) }}
          </template>

        </el-table-column>

        <el-table-column prop="default" label="操作" width="134" fixed="right" align="center">
          <template #default="scope">
            <el-button @click="handleDetailsClick(scope.row)" type="success" size="small">
              详情
            </el-button>
            <el-button @click="handleEditClick(scope.row)" type="primary" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_box mt-20">
        <el-pagination small :current-page.sync="currentPage" :page-size.sync="pageSize" :page-sizes="[10, 20, 30, 50]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  reactive,
  shallowRef,
  onUnmounted,
} from "vue";
// import { useStore } from "vuex"; 
import { ElMessageBox, ElMessage } from "element-plus";
// import type { UploadProps, UploadUserFile } from "element-plus";
import {
  WarningFilled,
  Plus,
  View,
  Delete,
  Edit,
  Search,
  Share,
  Upload,
} from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
// const store = useStore();
const iconPng = new URL("@/assets/img/index/pf.png", import.meta.url).href;
import {
  getLicenseListApi, licenseAdd,
  licenseEdit,
} from "@/api/resourceManagement";
import { useMousePosition } from "@/hooks/dateSelect";
const { timeType } = useMousePosition();
const formRef: any = ref(null);
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  licenseNumber: [{ required: true, message: "请输入展示号码", trigger: "blur" }],
  vehicleType: [
    {
      required: true,
      message: "请选择车辆种类",
      trigger: "blur",
    },
  ],
  licenseKind: [
    {
      required: true,
      message: "请输入车辆类型",
      trigger: "blur",
    },
  ],
  volume: [
    {
      required: true,
      message: "请输入车辆容积",
      trigger: "blur",
    },
  ],
};
const props: any = defineProps({});
onMounted(() => { });

onBeforeUnmount(() => { });
onUnmounted(() => { });
let dialogVisible = ref(false);
let dialogAddVisible = ref(false);
let form: any = ref({});
const radiopzq = ref("3");
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
// const page = ref({
//   total: 0,
//   pageSize: 10,
//   currentPage: 1
// })
let tableData = ref([]);
let tableAllData = ref([]);
let selectObj = ref({
  vehicleType: 99,
  key: null
});
const unitOptions = [
  {
    value: 0,
    label: "钩臂箱体运输车",
  },
  {
    value: 1,
    label: "厨余垃圾清运车",
  },
  {
    value: 2,
    label: "大件垃圾清运车",
  },
  {
    value: 3,
    label: "其他垃圾驳运车",
  },
  {
    value: 4,
    label: "厨余垃圾驳运车",
  },
  {
    value: 5,
    label: "三轮垃圾驳运车",
  },
  {
    value: 6,
    label: "维修作业车",
  },
  {
    value: 7,
    label: "管理工作车",
  },
];
const unitAllOptions = [
  {
    value: 99,
    label: "全部",
  },
  {
    value: 0,
    label: "钩臂箱体运输车",
  },
  {
    value: 1,
    label: "厨余垃圾清运车",
  },
  {
    value: 2,
    label: "大件垃圾清运车",
  },
  {
    value: 3,
    label: "其他垃圾驳运车",
  },
  {
    value: 4,
    label: "厨余垃圾驳运车",
  },
  {
    value: 5,
    label: "三轮垃圾驳运车",
  },
  {
    value: 6,
    label: "维修作业车",
  },
  {
    value: 7,
    label: "管理工作车",
  },
];
watch(
  timeType,
  () => {
    init();
  },
  {
    immediate: true,
  }
);

function init() {
  getLicenseList();

}
//牌照库- 根据关键字查询搜索，车属单位和车辆类型列表
async function getLicenseList() {
  tableData.value = [];
  let info = {
    pageNo: 1,
    pageSize: 10,
    key: null, //搜索值
    vehicle_type: 99, //车辆类型  全部
  };
  const res = await getLicenseListApi(info);
  console.log("牌照库", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  tableData.value = result?.records || [];
  // console.log("车牌列表-分页列表查询", tableData.value, result);
}
//牌照库- 根据关键字查询搜索，车属单位和车辆类型列表
async function getLicenseAllList() {
  tableAllData.value = [];
  // total.value = 0
  let info = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    key: selectObj.value.key || null, //搜索值
    vehicle_type: selectObj.value.vehicleType, //车辆类型  全部
  };
  const res = await getLicenseListApi(info);
  console.log("全部牌照库", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  tableAllData.value = result?.records || [];
  total.value = Number(result?.total) || 0;
}

// 搜索
function handleSelectClose() {
  getLicenseAllList()
}
// 重置
function handleReact() {
  currentPage.value = 1
  pageSize.value = 10
  selectObj.value = {
    vehicleType: 99,
    key: null
  }
  getLicenseAllList()
}
// 新增
const handleAddClick = () => {
  console.log(234124, form.value, dialogAddVisible.value);
  dialogAddVisible.value = true;
  form.value = {}
};
// 详情
const handleDetailsClick = (scope: any) => {
  dialogAddVisible.value = true;
  form.value = {
    licenseNumber: scope.license_number,
    vehicleType: scope.vehicle_type,
    licenseKind: scope.license_kind,
    volume: scope.volume,
    id: scope.id,
    disabled: true
  }
};
// 总的详情
const handleAllDetailsClick = () => {
  dialogVisible.value = true;
  getLicenseAllList();
};
// 编辑
const handleEditClick = (scope: any) => {
  dialogAddVisible.value = true;
  form.value = {
    licenseNumber: scope.license_number,
    vehicleType: scope.vehicle_type,
    licenseKind: scope.license_kind,
    volume: scope.volume,
    id: scope.id,
    disabled: false
  }
};
// 关闭
const handleClose = () => {
  form.value = {};
  dialogAddVisible.value = false;
};
// 关闭
const handleVisibleClose = () => {
  handleReact()
  dialogVisible.value = false;
};
// 删除
const handleDelClick = () => { };
const submitForm = () => {
  console.log(formRef.value, form.value);
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      form.value.licenseType = 0;
      delete form.value.disabled
      if (form.value?.id) {
        let res: any = await licenseEdit(form.value);
        if (res?.success || res?.data?.code === 200) {
          ElMessage.success("修改成功!")
          form.value = {};
          formRef.value && formRef.value.resetFields();
          getLicenseList();
          getLicenseAllList()
          handleClose()
        } else ElMessage.warning(res?.msg || res?.data?.message);
      } else {
        form.value.recordingTime = formatDateDay(new Date())
        let res: any = await licenseAdd(form.value);
        console.log(12312, res);

        if (res?.success || res?.data?.code === 200) {
          ElMessage.success("添加成功!")
          form.value = {};
          formRef.value && formRef.value.resetFields();
          getLicenseList();
          getLicenseAllList()
          handleClose()
        } else ElMessage.warning(res?.msg || res?.data?.message);
      }
      // ElMessageBox.confirm("确定要提交表单吗？", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then(() => {
      //     // 处理提交逻辑
      //     console.log(form.value);
      //     ElMessageBox.alert("提交成功", "提示", { type: "success" });
      //   })
      //   .catch(() => {
      //     // 取消提交逻辑
      //   });
    } else {
      return false;
    }
  })

};

// 联想 搜索数据 车辆类型
async function licenseKindQuerySearchAsync(queryString: any, cb: any): Promise<any> {
  let results;
  if (queryString) {
    let info = {
      key: queryString,
      pageNo: 1,
      pageSize: 99999,
      // license_type: 0, // 牌照类型 0车牌照 1箱牌照 2全部
      vehicle_type: 99, //车辆类型  全部
      unitId: null,
    };
    let res = await getLicenseListApi(info);
    let resList = res?.data?.result?.records || []
    resList.forEach((item: any) => {
      // item.value = item.license_kind;
      item.value = item.license_kind + '——' + item.identification_number;
    });
    console.log("车牌照 联想搜索", res, resList);
    results = resList;
  } else {
    results = [];
  }
  await cb(results);
}
function formatDateDay(e: any) {
  e = Number(e)
  /**时间戳转YYYY-MM-DD hh:mm:ss格式
   * @param {时间戳} e
   */
  try {
    e = e.replace(/-/g, "/");
  } catch (err) { }
  var date = new Date(e);
  var YY = date.getFullYear() + "-";
  var MM =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

  return YY + MM + DD;
}


//条数
function handleSizeChange(value: any) {
  pageSize.value = value; console.log('条数', value);
  getLicenseAllList()//调取接口
}
function handleCurrentChange(value: any) {
  //页码发生变化会触发，这个用来触发点击页码时触发的。
  currentPage.value = value; console.log('页码发生变化会触发', value);
  getLicenseAllList()//调取接口

}
</script>

<style lang="scss" scoped>
.daraBoardStreetAnalysis_content {
  height: 400px;

  .header_box {
    .add_icon {
      margin-right: 5px;
      cursor: pointer;
    }
  }

  .main_box {
    overflow-y: auto;
  }

  .el-radio.el-radio--large {
    height: 30px;
  }

  .el-upload__tip {
    font-size: 13px;
    margin-top: -30px;
    margin-left: 100px;
    color: #939191;
  }
}


.dialog_header::v-deep {
  // .select {}

  .el-select {
    height: 32px;
    line-height: 32px;
  }

  .el-input {
    height: 32px;
    line-height: 32px;
  }
}
</style>
<style>
.el-dialog__body {
  padding: 10px 20px 20px;
}
</style>